<?php

namespace App\Service\Third;

use App\Model\GuildManage\GuildWithdrawal;
use App\Model\Withdraw;
use App\Service\BaseService;
use WGCYunPay\Service\Des3Service;

class MstCallbackService extends  BaseService
{
    public function handle()
    {
        $notifyData = $this->request->all();
        log_info(__CLASS__.':MstCallbackService回调'.json_encode($notifyData));

        $config = config('mst.mst');

        $data = Des3Service::decode($notifyData['data'], $config['des3Key']);
        log_info(__CLASS__.':MstCallbackService解密'.json_encode($data));

        $orderId = $data['dealSerialNo'] ?? '';
        if (!$orderId) return;

        $updaInfo = [];
        if (isset($data['code']) && $data['code'] == 201) {
            $updaInfo['status'] = Withdraw::STATUS_OK;
            log_info(__CLASS__ . "==到账成功==orderId:{$orderId}");
        } else {
            $updaInfo['status'] = Withdraw::STATUS_YZH_ERR;
        }
        $updaInfo['yzh_detail'] = json_encode([
            'status' => $data['code'] ?? '-1',
            'message' => $data['msg'] ?? '未知错误',
            'cashoutStatus' => $data['cashoutStatus'] ?? '未知错误',
            'remark' => $data['remark'] ?? '未知错误',
        ]);
        log_info(__CLASS__ . "==OrderId:{$orderId}==OrderInfo:" . json_encode($data) . "==UpdateInfo:" . json_encode($updaInfo));

        $info = Withdraw::where('yzh_order_id', $orderId)->first();
        if (empty($info)) {
            $ret = GuildWithdrawal::where('yzh_order_id', $orderId)->limit(1)->update($updaInfo);
        } else {
            $ret = Withdraw::where('yzh_order_id', $orderId)->limit(1)->update($updaInfo);
        }

        return $data;

//        return $notifyData;
    }
}